package com.phkj.qdh.ui.fragment.mynotice

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.phkj.qdh.R
import com.phkj.qdh.bean.MyBaseInspectBean
import com.phkj.qdh.bean.MyBaseInspectDetailBean
import com.phkj.qdh.databinding.FragmentMyBaseNoticeDetailBinding
import com.phkj.qdh.ui.adapter.BaseInspectDetailAdapter
import com.phkj.qdh.ui.adapter.ImagerViewAdapter
import com.phkj.qdh.ui.dialog.CommonConfirmDialog
import com.phkj.qdh.ui.dialog.CommonConfirmListener
import com.phkj.qdh.ui.fragment.user.UserVM
import com.phkj.qdh.ui.fragment.user.getUserVMProvider
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.gone
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import com.phkj.qdh.utils.visible
import kotlinx.coroutines.flow.collectLatest
import java.util.HashMap

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 通告 基础详情
 */
class MyBaseNoticeDetailFragment : Fragment() {
    private var param1: MyBaseInspectBean? = null
    private var param2: String? = null
    private var _binding: FragmentMyBaseNoticeDetailBinding? = null
    private val binding get() = _binding!!
    private lateinit var vm: UserVM
    private var detailBean: MyBaseInspectDetailBean? = null
    private val iVAdapter by lazy { ImagerViewAdapter(true) }
    private val baseInspectDetailAdapter by lazy { BaseInspectDetailAdapter() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getParcelable(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentMyBaseNoticeDetailBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getUserVMProvider())[UserVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            rvDetail.run {
                layoutManager = LinearLayoutManager(requireContext())
                adapter = baseInspectDetailAdapter
            }
            rvBaseSubmit.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(requireContext(), R.color.transparent),
                        28,
                        RecyclerView.HORIZONTAL
                    )
                )
                adapter = iVAdapter
            }
            btnNo.setOnClickListener {
                val dialog = CommonConfirmDialog.getInstance("驳回", "确定要驳回吗")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        val map = HashMap<String, Any?>()
                        map["id"] = detailBean?.id
                        map["state"] = 4
                        vm.editBaseDetail("驳回成功",map)
                    }

                    override fun dCancel() {
                    }

                })
                dialog.show(parentFragmentManager, "")
            }

        }
        param1?.let {
            binding.run {
//                tvSort1.text = it.keyPointTypeName
//                baseInspectDetailAdapter.submitList(it.detail)
//                tvRisk.text = if (it.anyRisk == 0) "有" else "无"
//                tvState.text = it.stateName
//                val sb = StringBuilder()
//                it.policeNameIdVO.forEach { p ->
//                    sb.append(p.name)
//                    sb.append("、")
//                }
//                tvMingjing.text =
//                    if (sb.length > 1) sb.deleteCharAt(sb.length - 1).toString() else ""
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.baseDetail.collectLatest {
                detailBean = it
                binding.run {
                    tvSort1.text = it.keyPointTypeName
                    tvSecond.text = it.lastKeyPointTypeName
                    baseInspectDetailAdapter.submitList(it.keyPointDataList)
                    tvRisk.text = if (it.anyRisk == 0) "有" else "无"
                    tvState.text = if (it.rectification == 0) "待整改" else "已整改"
                    tvMingjing.text =
                        it.checkUsers.toString().replace("[", "").replace(",", " ").replace("]", "")
                    tvBanFa.text = it.policeName
                    tvFen.text = it.policeScore.toString()

                    if (it.state == 2) {
                        btnOk.visible()
                        btnOk.text = "立即整改"
                        btnNo.visible()
                    } else if (it.state > 2) {
                        btnNo.gone()
                    }
                    when (it.state) {
                       1, 2,4 -> {
                            btnOk.visible()
                            btnOk.text = "立即整改"
                            btnNo.visible()
                            btnOk.setOnClickListener {
                                parentFragmentManager.commit {
                                    addToBackStack("")
                                    replace(id, MyBaseInspectFeedbackFragment.newInstance(detailBean!!.id.toString(), ""))
                                    setReorderingAllowed(true)
                                }
                            }
                        }

                        3 -> {
                            btnOk.text = "已反馈"
                            btnNo.gone()
                        }

                        5 -> {
                            btnOk.text = "已退回"
                            btnNo.gone()
                        }

                        6 -> {
                            btnOk.text = "已完成"
                            btnNo.gone()
                        }
                        else -> {
                            btnOk.visible()
                            btnOk.text = "记录"
                            btnNo.gone()
                        }
                    }
                }
                iVAdapter.submitList(it.imageUrl.split(","))
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.baseEditResult.collectLatest {
                if (it.equals("驳回成功")){
                    parentFragmentManager.popBackStack()
                }
            }
        }
        vm.getBaseDetail(param1?.id!!)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: MyBaseInspectBean, param2: String) =
            MyBaseNoticeDetailFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}